package com.info33.platform.common.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 实现防盗链接
 *
 * @author Administrator
 */
@WebFilter(urlPatterns = {"/assets/*"}, filterName = "RefererFilter")
public class RefererFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter初始化...");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        // 禁用缓存
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragrma", "no-cache");
        response.setDateHeader("Expires", 0);

        // 从请求头中获得的请求全地址
        String referer = request.getHeader("referer");

        // 如果为referer来源为 null, 则表示直接从浏览器地地址输入的
        if (referer == null) {
            //-------------用来富文本文档下载、文档预览 链接放行begin-----------------------
            if ("preview=true".equals(request.getQueryString())) {
                // 放行
                chain.doFilter(request, response);
                return;
            }
            //-------------用来富文本文档下载、文档预览 链接放行finish-----------------------
            request.getRequestDispatcher("/index.html").forward(request, response);
            return;

        }

        // 放行
        chain.doFilter(request, response);

    }

    @Override
    public void destroy() {
        System.out.println("Filter销毁...");
    }

}
